package system

import (
	"5title_gin/global"
	"5title_gin/internal/model/system/menu"
	"5title_gin/internal/model/system/roles"
	"5title_gin/pkg/db/crud"
	"5title_gin/pkg/tree"
	"errors"
)

// MenuService 菜单服务
type MenuService struct {
	menuCrud     *crud.CRUD[menu.SysMenu]
	menuRoleCrud *crud.CRUD[roles.SysRoleMenu]
}

func NewMenuService() *MenuService {
	return &MenuService{
		menuCrud:     crud.NewCRUD[menu.SysMenu](global.DB),
		menuRoleCrud: crud.NewCRUD[roles.SysRoleMenu](global.DB),
	}
}

// GetMenuList 获取菜单列表，返回树形结构
func (s *MenuService) GetMenuList(roleID uint) ([]*menu.SysMenuVo, error) {
	var menuIDs []uint
	var menuList []menu.SysMenu
	var err error

	if roleID != 1 {
		// 普通角色，获取该角色的菜单ID
		roleMenus, err := s.menuRoleCrud.GetAll().Select("menu_id").Where("role_id = ?", roleID).Find()
		if err != nil {
			return nil, errors.New("获取角色菜单列表失败")
		}

		// 提取菜单ID
		for _, rm := range roleMenus {
			menuIDs = append(menuIDs, rm.MenuId)
		}
	}

	// 根据条件获取菜单列表
	if len(menuIDs) == 0 {
		// 如果没有指定菜单ID，获取所有状态为1的菜单
		menuList, err = s.menuCrud.GetAll().Find()
	} else {
		// 根据菜单ID获取菜单
		menuList, err = s.menuCrud.GetAll().Where("id IN ?", menuIDs).Find()
	}

	if err != nil {
		return nil, errors.New("获取菜单列表失败")
	}

	// 将SysMenu转换为SysMenuVo
	menuVos := make([]*menu.MenuTreeNode, 0, len(menuList))
	for _, m := range menuList {
		// 创建MenuMeta
		meta := menu.MenuMeta{
			Title:             m.Title,
			Icon:              m.Icon,
			ShowBadge:         m.ShowBadge,
			IsHide:            m.IsHide,
			IsHideTab:         m.IsHideTab,
			Link:              m.Link,
			IsIframe:          m.IsFrame,
			KeepAlive:         m.KeepAlive,
			IsInMainContainer: m.IsInMainContainer,
		}

		// 如果有ShowTextBadge，转换为字符串
		if m.ShowTextBadge {
			meta.ShowTextBadge = "new"
		}

		// 创建MenuTreeNode
		menuVo := &menu.MenuTreeNode{
			SysMenuVo: menu.SysMenuVo{
				ID:        m.ID,
				Path:      m.Path,
				Name:      m.Name,
				Component: m.Component,
				Meta:      meta,
				ParentID:  m.ParentId,
				Sort:      m.OrderNum,
				Status:    1, // 假设所有获取到的菜单都是启用状态
				CreatedAt: m.CreatedAt.Unix(),
				UpdatedAt: m.UpdatedAt.Unix(),
				Children:  []*menu.SysMenuVo{},
			},
		}

		menuVos = append(menuVos, menuVo)
	}

	// 使用tree工具构建树形结构
	treeBuilder := tree.NewTree(menuVos)
	treeData := treeBuilder.BuildTree(0) // 假设根菜单的parent_id为0

	// 将MenuTreeNode转换为SysMenuVo
	result := make([]*menu.SysMenuVo, len(treeData))
	for i, node := range treeData {
		result[i] = &node.SysMenuVo
	}

	return result, nil
}
